package cn.lanqiao.rbac.config;

//public class ResponseEntityRedisSerializer extends Jackson2JsonRedisSerializer {
//
//    public ResponseEntityRedisSerializer() {
//        super(ResponseEntity.class);
//    }
//
//    public byte[] serialize(ResponseEntity<?> responseEntity) throws SerializationException {
//        // 序列化ResponseEntity的主体内容
//        return super.serialize(responseEntity.getBody());
//    }
//
//    @Override
//    public ResponseEntity<?> deserialize(byte[] bytes) throws SerializationException {
//        // 反序列化时，你需要提供完整的ResponseEntity，可能需要手动设置状态码和头信息
//        Object body = super.deserialize(bytes);
//        // 假设你有方法来获取状态码和头信息，你可以这样构建ResponseEntity
//        return ResponseEntity.status(200).body(body);
//    }
//}

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;

import java.io.IOException;

public class ResponseEntityRedisSerializer implements RedisSerializer<ResponseEntity<?>> {

    private final ObjectMapper objectMapper;

    public ResponseEntityRedisSerializer(ObjectMapper objectMapper) {
        Assert.notNull(objectMapper, "ObjectMapper must not be null");
        this.objectMapper = objectMapper;
    }

    @Override
    public byte[] serialize(ResponseEntity<?> entity) throws SerializationException {
        try {
            return objectMapper.writeValueAsBytes(entity);
        } catch (JsonProcessingException e) {
            throw new SerializationException("Error serializing ResponseEntity", e);
        }
    }

    @Override
    public ResponseEntity<?> deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, new TypeReference<ResponseEntity<?>>() {});
        } catch (IOException e) {
            throw new SerializationException("Error deserializing ResponseEntity", e);
        }
    }
}
